import React, { useState, useEffect } from 'react'
import Container from 'components/Container'
import CodeDemo from 'components/CodeDemo'
import MarkdownView from './hooks/MarkdownView'
import md5 from 'js-md5'
import style from './index.module.css'
import desmd from './description.md'

/**
 * 渲染代码块结构
 * @param {*} list
 */
function render(list) {
  const navs = [],
    comps = []
  list.forEach((comp) => {
    const { Example, compstr, title, description } = comp
    const config = { comp: <Example />, title, code: compstr, description }
    const hash = md5(compstr).substring(0, 6)
    navs.push(
      <a key={hash} href={'#' + hash}>
        {title}
      </a>,
    )
    comps.push(
      <div key={hash}>
        <h2 id={hash}>{title}</h2>
        <CodeDemo {...config} />
      </div>,
    )
  })
  return { navs, comps }
}

const hooks = [
  'useState',
  'useEffect',
  'useReducer',
  'useCallback',
  'useContext',
  'useImperativeHandle',
  'useRef',
  'useMemo',
  'useLayoutEffect',
  'useDebugValue',
  'useDispatch',
]

export default function Hooks() {
  const [list, setlist] = useState([])
  useEffect(() => {
    const compArr = []
    const comps = require.context('./hooks', true, /index\.js$/)
    comps.keys().forEach((key) => {
      const title = key.split('/')[1]
      compArr.push({ title, ...comps(key) })
    })
    setlist(compArr.sort((a, b) => a.order - b.order))
  }, [])
  const { navs, comps } = render(list)
  return (
    <Container title="React hooks" className={style.hooks_container}>
      <div className={style.description}>
          <MarkdownView url={desmd}/>
        </div>
      <div>{hooks.join("   ")}</div>
      <div className={style.navs}>{navs}</div>
      {comps}
    </Container>
  )
}
